<template>
  <!-- 全局背景层 -->
  <view class="bg-layer"></view>
  
  <view class="shop-container">
    <!-- 顶部栏 -->
    <view class="shop-header">
      <text class="shop-title">积分商城</text>
      <view class="points-container">
        <uni-icons type="star-filled" size="18" color="#FFD700"></uni-icons>
        <text class="points-value">{{ safeUser.points }}</text>
      </view>
    </view>

    <!-- 操作栏 -->
    <view class="action-bar">
      <button 
        class="history-button"
        @click="navigateToExchangeHistory"
        @touchstart="buttonScale(0.95, $event)"
        @touchend="buttonScale(1, $event)"
      >
        <uni-icons type="list" size="16" color="#fff"></uni-icons>
        <text>兑换记录</text>
      </button>
    </view>

    <!-- 商品列表 -->
    <scroll-view 
      scroll-y 
      class="item-scroll"
      refresher-enabled
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <!-- 加载状态 -->
      <view v-if="loading && page === 1" class="loading-state">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="!loading && items.length === 0" class="empty-state">
        <image src="/static/empty-shop.png" mode="aspectFit"></image>
        <text class="empty-text">暂无奖品，敬请期待</text>
        <text class="empty-tip">上新奖品会第一时间通知哦~</text>
      </view>

      <!-- 商品列表 -->
      <view v-else class="item-grid">
        <view 
          v-for="item in items" 
          :key="item._id"
          class="item-card"
          @click="showItemDetail(item)"
          @touchstart="cardTouchStart(item._id)"
          @touchend="cardTouchEnd(item._id)"
        >
          <view class="item-image-container">
            <image class="item-image" :src="item.image || '/static/default-item.png'" mode="aspectFill" />
            <view class="item-badge" v-if="item.stock <= 0">已兑完</view>
            <view class="hot-badge" v-if="item.isHot">
              <uni-icons type="fire" size="14" color="#fff"></uni-icons>
            </view>
          </view>
          
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <view class="item-meta">
              <view class="points-tag">
                <uni-icons type="star-filled" size="14" color="#FFD700"></uni-icons>
                <text>{{ item.points || 0 }}</text>
              </view>
              <text class="item-stock">剩余 {{ item.stock || 0 }} 件</text>
            </view>
            <button 
              class="exchange-button"
              :class="{ 
                'disabled': item.stock <= 0 || safeUser.points < item.points,
                'pulse': !(item.stock <= 0 || safeUser.points < item.points)
              }"
              @click.stop="handleExchange(item)"
            >
              {{ getButtonText(item) }}
            </button>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <uni-load-more 
        v-if="items.length > 0"
        :status="loadStatus" 
        :icon-size="16"
        color="#4a90e2"
      />
    </scroll-view>

    <!-- 兑换确认弹窗 -->
    <uni-popup ref="exchangePopup" type="dialog" background-color="rgba(0,0,0,0.5)">
      <uni-popup-dialog 
        v-if="selectedItem._id"
        mode="base"
        title="确认兑换"
        :content="`确定要兑换【${selectedItem.name}】吗？`"
        confirm-text="确认兑换"
        cancel-text="再想想"
        @confirm="confirmExchange"
        @close="cancelExchange"
      >
        <view class="dialog-content">
          <image class="dialog-image" :src="selectedItem.image || '/static/default-item.png'" mode="aspectFit"></image>
          <view class="points-cost">
            <text>将消耗</text>
            <view class="points-value">
              <uni-icons type="star-filled" size="18" color="#FFD700"></uni-icons>
              <text>{{ selectedItem.points || 0 }}</text>
            </view>
            <text>积分</text>
          </view>
          <text class="stock-info">当前剩余: {{ selectedItem.stock || 0 }}件</text>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 用户数据确保有安全结构
      user: null,
      items: [],
      loading: false,
      loadStatus: 'more',
      selectedItem: {
        _id: '',
        name: '',
        points: 0,
        stock: 0,
        image: ''
      },
      page: 1,
      pageSize: 10,
      exchanging: false
    }
  },
  computed: {
    // 安全访问用户数据的计算属性
    safeUser() {
      return this.user || { 
        id: '',
        points: 0,
        name: '未登录用户'
      }
    }
  },
  onLoad() {
    this.initData();
  },
  onShow() {
    if (!this.user) {
      this.checkLoginStatus();
    }
  },
  methods: {
    async initData() {
      await this.checkLoginStatus();
      this.loadItems();
    },

    async checkLoginStatus() {
      try {
        const user = uni.getStorageSync('user');
        if (!user?.id) {
          this.showLoginModal();
          throw new Error('用户未登录');
        }
        this.user = user;
        await this.getUserPoints();
      } catch (e) {
        console.error('登录检查失败:', e);
        this.user = null;
      }
    },
    
    showLoginModal() {
      uni.showModal({
        title: '需要登录',
        content: '请先登录才能访问积分商城',
        confirmText: '去登录',
        cancelText: '暂不登录',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({ url: '/pages/student/login' });
          } else {
            uni.navigateBack();
          }
        }
      });
    },

    async getUserPoints() {
      if (!this.user?.id) return;
      
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserPoints',
          data: { 
            user_id: this.user.id
          }
        });
        
        if (res.result.code === 0) {
          this.user = {
            ...this.user,
            points: res.result.data.points || 0,
            consecutive_days: res.result.data.consecutiveDays || 0
          };
          uni.setStorageSync('user', this.user);
        }
      } catch (e) {
        console.error('获取积分失败:', e);
      }
    },

    async loadItems() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const res = await uniCloud.callFunction({
          name: 'getItems',
          data: {
            page: this.page,
            pageSize: this.pageSize
          }
        });
        
        if (res.result.code === 0) {
          this.items = this.page === 1 
            ? res.result.data 
            : [...this.items, ...res.result.data];
          
          this.loadStatus = res.result.data.length < this.pageSize ? 'noMore' : 'more';
        }
      } catch (e) {
        console.error('商品加载失败:', e);
        uni.showToast({ title: '加载失败，请重试', icon: 'none' });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },

    onRefresh() {
      this.page = 1;
      this.loadStatus = 'more';
      this.loadItems();
    },

    loadMore() {
      if (this.loadStatus === 'more' && !this.loading) {
        this.page++;
        this.loadItems();
      }
    },

    getButtonText(item) {
      if (!this.user) return '请先登录';
      if (item.stock <= 0) return '已兑完';
      if (this.safeUser.points < item.points) return '积分不足';
      return '立即兑换';
    },

    handleExchange(item) {
      if (!this.user) {
        this.showLoginModal();
        return;
      }
      
      if (item.stock <= 0 || this.safeUser.points < item.points || this.exchanging) return;
      
      this.selectedItem = { ...item };
      this.$refs.exchangePopup.open();
    },

    async confirmExchange() {
      if (!this.selectedItem._id || this.exchanging || !this.user) return;
      
      this.exchanging = true;
      uni.showLoading({ title: '兑换中...', mask: true });
      
      try {
        const res = await uniCloud.callFunction({
          name: 'exchangeItem',
          data: {
            user_id: this.user.id,
            item_id: this.selectedItem._id
          }
        });
        
        if (res.result.code === 0) {
          // 更新用户积分
          this.user.points = res.result.data.points;
          uni.setStorageSync('user', this.user);
          
          // 更新本地商品库存
          this.items = this.items.map(item => {
            if (item._id === this.selectedItem._id) {
              return { ...item, stock: res.result.data.new_stock };
            }
            return item;
          });
          
          uni.showToast({ 
            title: `兑换成功，消耗 ${this.selectedItem.points} 积分`, 
            icon: 'success'
          });
        } else {
          throw new Error(res.result.msg || '兑换失败');
        }
      } catch (e) {
        console.error('兑换出错:', e);
        uni.showToast({ 
          title: e.message,
          icon: 'none'
        });
      } finally {
        this.exchanging = false;
        uni.hideLoading();
        this.$refs.exchangePopup.close();
      }
    },

    cancelExchange() {
      this.selectedItem = {
        _id: '',
        name: '',
        points: 0,
        stock: 0,
        image: ''
      };
    },

    navigateToExchangeHistory() {
      if (!this.user) {
        this.showLoginModal();
        return;
      }
      uni.navigateTo({ url: '/pages/student/exchange-history' });
    },

    showItemDetail(item) {
      uni.navigateTo({
        url: `/pages/student/item-detail?id=${item._id}`
      });
    },

    navigateTo(url) {
      uni.navigateTo({ url });
    },

    // UI交互方法
    buttonScale(scale, e) {
      const currentTarget = e?.currentTarget;
      if (!currentTarget) return;
      
      currentTarget.animate([
        { transform: `scale(${scale})` }
      ], { 
        duration: 200,
        fill: 'forwards' 
      });
    },
    
    cardTouchStart(id) {
      const element = this.getCardElement(id);
      if (element) {
        element.animate([
          { transform: 'scale(1)' },
          { transform: 'scale(0.98)' }
        ], 100);
      }
    },
    
    cardTouchEnd(id) {
      const element = this.getCardElement(id);
      if (element) {
        element.animate([
          { transform: 'scale(0.98)' },
          { transform: 'scale(1)' }
        ], 150);
      }
    },
    
    getCardElement(id) {
      return uni.createSelectorQuery()
        .in(this)
        .select(`.item-card[data-id="${id}"]`);
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 30vh;
  background: linear-gradient(135deg, #4a90e2 0%, #5aa1ff 100%);
  z-index: 0;
  border-radius: 0 0 20% 20%;
}

.shop-container {
  position: relative;
  min-height: 100vh;
  z-index: 1;
  padding-bottom: env(safe-area-inset-bottom);
}

/* 顶部标题栏 */
.shop-header {
  position: relative;
  padding: 30rpx;
  margin: 20rpx;
  background: rgba(255,255,255,0.95);
  border-radius: 16px;
  box-shadow: 0 6px 18px rgba(74, 144, 226, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  backdrop-filter: blur(10px);
}

.shop-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
}

.points-container {
  display: flex;
  align-items: center;
  background: rgba(74, 144, 226, 0.1);
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s;
}

.points-container:active {
  background: rgba(74, 144, 226, 0.2);
}

.points-value {
  font-size: 16px;
  font-weight: 600;
  color: #4a90e2;
  margin: 0 8px;
}

/* 操作栏 */
.action-bar {
  padding: 0 20rpx 20rpx;
  display: flex;
  justify-content: flex-end;
}

.history-button {
  background: linear-gradient(90deg, #FF9800, #FFB74D);
  color: white;
  border-radius: 50rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  padding: 0 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
  border: none;
}

.history-button text {
  margin-left: 10rpx;
}

/* 商品列表 */
.item-scroll {
  flex: 1;
  padding: 0 20rpx 20rpx;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(74, 144, 226, 0.2);
  border-top-color: #4a90e2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
}

.empty-state image {
  width: 300rpx;
  height: 300rpx;
  opacity: 0.8;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin-top: 20px;
}

.empty-tip {
  font-size: 14px;
  color: #999;
  margin-top: 8px;
}

.item-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding-bottom: 20rpx;
}

.item-card {
  background: rgba(255,255,255,0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(0,0,0,0.05);
  transition: all 0.3s;
  backdrop-filter: blur(10px);
}

.item-image-container {
  position: relative;
  width: 100%;
  height: 300rpx;
}

.item-image {
  width: 100%;
  height: 100%;
}

.item-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
}

.hot-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  background: linear-gradient(90deg, #FF5252, #FF4081);
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-info {
  padding: 16px;
}

.item-name {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 42px;
  line-height: 21px;
  margin-bottom: 12px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.points-tag {
  display: flex;
  align-items: center;
  background: rgba(255, 215, 0, 0.1);
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 14px;
  color: #FF9800;
}

.item-stock {
  font-size: 12px;
  color: #999;
}

.exchange-button {
  background: linear-gradient(90deg, #4a90e2, #5aa1ff);
  color: white;
  border-radius: 20px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  border: none;
  transition: all 0.3s;
}

.exchange-button.pulse {
  animation: pulse 2s infinite;
}

.exchange-button.disabled {
  background: #eee;
  color: #999;
}

/* 弹窗样式 */
.dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.dialog-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.points-cost {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 16px;
  color: #666;
}

.points-value {
  display: flex;
  align-items: center;
  margin: 0 6px;
  font-weight: 600;
  color: #FF9800;
}

.stock-info {
  font-size: 14px;
  color: #999;
}

/* 动画效果 */
@keyframes spin {
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(74, 144, 226, 0.4); }
  70% { box-shadow: 0 0 0 10px rgba(74, 144, 226, 0); }
  100% { box-shadow: 0 0 0 0 rgba(74, 144, 226, 0); }
}
</style>